package com.gxa.employment.common;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gxa.employment.entity.dto.ClazzServiceAddDto;
import com.gxa.employment.entity.pojo.Clazz;
import com.gxa.employment.entity.pojo.Major;
import com.gxa.employment.service.ClazzService;
import com.gxa.employment.service.MajorService;
import org.springframework.beans.BeanUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义监听器，用于处理学生信息的导入
 */
public class ClazzDataListener extends AnalysisEventListener<ClazzServiceAddDto> {

    private  MajorService majorService;
    private final ClazzService clazzService;
    private List<ClazzServiceAddDto> failedRecords = new ArrayList<>();

    public ClazzDataListener(ClazzService clazzService,MajorService majorService) {
        // 将传入的StudentService赋值给类的成员变量studentService
        this.clazzService = clazzService;
        this.majorService = majorService;
    }


    @Override
    public void invoke(ClazzServiceAddDto clazzAddDto, AnalysisContext context) {
        Clazz clazz = new Clazz();
        clazz.setClazzEnd(clazzAddDto.getClazzStart().plusDays(clazzAddDto.getClazzDays()));
        clazz.setCreated(LocalDateTime.now());
        LambdaQueryWrapper<Major> userLambdaQueryWrapper = Wrappers.lambdaQuery(Major.class);

        // 设置查询条件：班级ID等于传入的clazzNotEmploymentDto中的班级ID

        userLambdaQueryWrapper.eq(Major::getMajorName, clazzAddDto.getMajorName());
        // 设置查询条件：学生状态等于传入的clazzNotEmploymentDto中的学生状态


        Major one = majorService.getOne(userLambdaQueryWrapper);

        clazz.setMajorId(one.getMajorId());

        BeanUtils.copyProperties(clazzAddDto,clazz);
        try {
            // 调用studentService的save方法保存学生信息
            clazzService.save(clazz);
        } catch (Exception e) {
            // 如果出现异常，则将studentDto添加到failedRecords中
            failedRecords.add(clazzAddDto);
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 如果存在失败的记录
        if (!failedRecords.isEmpty()) {
            // 输出失败的记录数量
            System.out.println("Failed to import " + failedRecords.size() + " records.");
        }
    }


    public List<ClazzServiceAddDto> getFailedRecords() {
        // 返回失败的记录列表
        return failedRecords;
    }

}
